import { calcOpenModeStyle } from '@ibiz-template/core';
import { SearchFormController } from '@ibiz-template/runtime';

/**
 * 高级搜索表单控制器
 *
 * @export
 * @class AdvancedSearchFormController
 * @extends {SearchFormController}
 */
export class AdvancedSearchFormController extends SearchFormController {
  /**
   * 常驻表单项识别标识
   *
   * @type {string}
   * @memberof AdvancedSearchFormController
   */
  permanentKey: string = 'permanent';

  /**
   * 初始化state
   *
   * @protected
   * @memberof AdvancedSearchFormController
   */
  protected initState(): void {
    super.initState();
    this.calcDefaultOptions();
  }

  /**
   * 监听回车事件
   * 
   * @param {KeyboardEvent} event
   * @return {*}  {Promise<void>}
   * @memberof AdvancedSearchFormController
   */
  async onKeyUp(event: KeyboardEvent): Promise<void> {
    const e = event || window.event;
    //  回车触发搜索
    if (e && e.code === 'Enter') {
      await this.search();
    }
  }

  /**
   * 计算默认选项
   *
   * @memberof AdvancedSearchFormController
   */
  calcDefaultOptions(): void {
    if (this.model.controlParam?.ctrlParams) {
      const { ctrlParams } = this.model.controlParam;
      Object.keys(ctrlParams).forEach(key => {
        const value = ctrlParams[key];
        switch (key.toLowerCase()) {
          case 'width':
            if (value) {
              if (value.includes('px') || value.includes('%')) {
                (this.state as IParams).width = value;
              } else {
                (this.state as IParams).width = calcOpenModeStyle(
                  value,
                  'modal',
                );
              }
            }
            break;
          case 'height':
            if (value) {
              if (value.includes('px') || value.includes('%')) {
                (this.state as IParams).height = value;
              } else {
                (this.state as IParams).height = calcOpenModeStyle(
                  value,
                  'modal',
                );
              }
            }
            break;
          default:
            break;
        }
      });
    }
  }

  /**
   * 重置搜索表单
   *
   * @memberof AdvancedSearchFormController
   */
  async reset(): Promise<void> {
    await this.load();
  }
}
